package mdm.uniauto.me.route;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Set;

/**
 * @Date 创建时间 ： 2017/10/16
 * @Author 作者：sjt
 * @Description 描述：操作operate 的manager
 * @Version 版本
 */

public class RouteManager {
    private static RouteManager manager;
    private HashMap<String, IOperate> operatePool;

    private RouteManager() {
        operatePool = new HashMap<>();
        initDefaultOperate();
    }

    public static RouteManager getInstance() {
        if (manager == null) {
            synchronized (RouteManager.class) {
                if (manager == null) {
                    manager = new RouteManager();
                }
            }
        }
        return manager;
    }

    /**
     * 初始化默认的operate
     */
    private void initDefaultOperate() {
        if (operatePool != null) {
            operatePool.put(ActivityIntentOperate.ACTIVITY_PROTOCOL, new ActivityIntentOperate());
            operatePool.put(ServiceIntentOperate.SERVICE_PROTOCOL, new ActivityIntentOperate());
            operatePool.put(ReceiverIntentOperate.RECEIVER_PROTOCOL,new ReceiverIntentOperate());
        }
    }
    /**
     * 根据Uri获取路由操作类
     * @param uri 路由地址
     */
    public  <T,V> IOperate<T,V> getOperator(String uri){
        IOperate<T,V> operator = null;
        if (operatePool != null){
            Set<String> protocols = operatePool.keySet();
            for (String protocol :
                    protocols) {
                if (uri.startsWith(protocol)){
                    operator = operatePool.get(protocol);
                    break;
                }
            }
        }
        return operator;
    }
    /**
     * 检查当前路由操作 是否存在
     * @param  uri 路由地址
     * @return false 不存在 true 存在
     */
    public boolean checkOperatorForURI(String uri){
        if (!TextUtils.isEmpty(uri)){
            IOperate<?, ?> operator = getOperator(uri);
            if (operator == null){
                throw new NullPointerException("can't find target operate by "+uri);
            }
            return true;
        }else {
            throw new NullPointerException("uri is empty");
        }
    }

    /**
     * 将class 放到指定的operate里面
     * @param uri
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> RouteManager putTargetUri(String uri, Class<T> clazz) {
        if (checkOperatorForURI(uri)){
            IOperate<T, ?> operator = getOperator(uri);
            operator.put(uri,clazz);
        }
        return manager;
    }
}
